const app = getApp();
const commonRequst = require('/customRequst.js');
const commonUser = require('/commonUser.js');
let userToken = '';

class Chat{
  //连接
  ws = {
    socketTask: null,
    Timer: null,
    ErrorMsg: [],//发送失败的消息
    MaxRetryCount: 3,
    CurrentRetryCount: 0,
    url: null,
    ReConnection:true
  };
  config;
  url = null;
  session_id = 0;
  bus_id = 0;
  msg_id = 0;
  session_info=null;
  chat_window = false;
  session_user = null;
  isTipsWarning = false;
  windowsobj = null;
  init(){
    let that = this;
    //判断用户是否已经登录
    userToken = commonUser.getUserToken();
    if(userToken == ''){
      wx.showModal({
        title: '登录提示',
        content:'您还未登录，请先登录！',
        success:function(res){
          if(res.confirm){
            wx.navigateTo({
              url: '/pages/users/login/index',
            });
          }
        }
      })
    };
    //获取聊天初始化数据
    let initUrl = that.bindUrl('init');
    commonRequst.getDomainRequest(initUrl,'').then(function(re){
     if(re.code == 1){
        //请求成功--赋值到配置中
        that.config = re.data;
        //连接webscoket
        that.ws.url = that.bindUrl('wss');
        if (!that.ws.socketTask || that.ws.socketTask.readyState == 3 || that.ws.socketTask.readyState == 2) {
          that.connectSocket();
        }
        //判断是否有新消息
        if (re.data.new_msg_num) {
          if(!that.chat_window){
            that.windowsobj.handleNewMessage(re.data);
          } 
      }
     }else{
       return;
     }
    },function(res) {
      return;
    })
  };

  //连接WebSocket
  connectSocket(){
    let that = this;
    if(that.ws.url == null || that.ws.url == undefined || that.ws.url == ''){
      return ;
    }
    //判断是否创建连接
    if(app.globalData.chat.socketTask){
        that.ws.socketTask = app.globalData.chat.socketTask;
    }else{
        //创建链接
        that.ws.socketTask = wx.connectSocket({url: that.ws.url});
        //绑定全局
        app.globalData.chat.socketTask = that.ws.socketTask;
    }

    //监听连接打开
    that.ws.socketTask.onOpen(function(header,profile){
        if(that.ws.CurrentRetryCount > 3){
          return;
        }
        // 重新发送--失败的消息
        if (that.ws.ErrorMsg.length > 0) {
            for (let i in that.ws.ErrorMsg) {
                that.sendMessage(JSON.parse(that.ws.ErrorMsg[i]));
            }
            that.ws.ErrorMsg = [];
        }
        //清理定时器
        if (that.ws.Timer != null) {
            clearInterval(that.ws.Timer);
        }
        //定时发送心跳
        that.ws.Timer = setInterval(function() {
          that.sendMessage();
        }.bind(that),28000);
    });

    //监听接收到服务器消息
    that.ws.socketTask.onMessage(function(evt){
      let data = JSON.parse(evt.data);
      if (data.code == 0) {
         wx.showToast({
           title: data.msg,
         })
      };
      that.handleMessage(data);
    });

    //监听断开连接
    that.ws.socketTask.onClose(function(code,reason){
      console.log('连接已经断开');
      if (that.ws.Timer != null) {
        clearInterval(that.ws.Timer);
      }
      if (that.ws.MaxRetryCount) {
          //每3秒重新连接一次
          that.ws.Timer = setInterval(function() {
            that.retryWebSocket();
          }.bind(that),100);
      }
    });
    
    //监听连接错误信息
    that.ws.socketTask.onError(function(errMsg){
      console.log('服务已停止');
      console.log(errMsg);
      that.ws.CurrentRetryCount = 3;
      that.ws.ReConnection = false;
    });

  };
  //发送聊天消息
  sendMessage(message){
    let that =this;
    if (!message) {
      message = {c: 'Message', a: 'ping'};
    }
    message = JSON.stringify(message);
    if (that.ws.socketTask && that.ws.socketTask.readyState == 1) {
      that.ws.socketTask.send({
        data:message,
        success:function(res) {
        },
        fail:function(re){
          //消息发送失败--添加到消息失败队列中
          that.ws.ErrorMsg.push(message);
        }
      });
    }else {
        that.ws.ErrorMsg.push(message);
        that.retryWebSocket();
    }
  }

  //处理服务器推送消息
  handleMessage(data){
    let that = this;
    that.windowsobj.handleChatMag(data);
  }
  //重新连接
  retryWebSocket(){
    let that = this;
    if (that.ws.CurrentRetryCount < that.ws.MaxRetryCount) {
      that.ws.CurrentRetryCount ++ ;
      that.connectSocket();
    }else {
      if (that.ws.Timer != null) {
          clearInterval(that.ws.Timer);
      }
      if (that.ws.ReConnection) {
        that.ws.Timer = setInterval(function () {
          that.connectSocket();
        }.bind(that), 10000);
      }
    }
  }

  //绑定聊天当前窗口
  bindWindow(obj){
    let that = this;
    that.windowsobj = obj;
  }

  //绑定请求url
  bindUrl(type){
    let that = this;
    let url = null;
    switch (type) {
        case 'wss':
          let token = '&token=' + that.config.token_list.fastchat_token;
          url = 'ws://' + app.globalData.chat.url + ':' + app.globalData.chat.wsport + '?modulename=' + app.globalData.chat.model + token;
          break;
        case 'init':
          url = "http://" + app.globalData.chat.url  + '/index/index/initwebscoket?modulename=' + app.globalData.chat.model + '&user_token=' + userToken;
          break;
        case 'upload':
          url = "http://" + app.globalData.chat.url + '/index/upload/index?modulename=' + app.globalData.chat.model;
           break;
        case 'load_message_prompt':
          url = "http://" + app.globalData.chat.url  + '/index/common/load_message_prompt?modulename=' + app.globalData.chat.model;
          break;
    }
    return url;
  }
}

export{
  Chat
}

